<template>
    <view class="login-container">
        <!-- 头部区域 -->
        <view class="login-header">
            <view class="login-logo">
                <image src="/static/logo.png" mode="aspectFit"></image>
                <text class="logo-text">MoeConnect</text>
            </view>
            <text class="login-title">登录</text>
            <text class="login-subtitle">欢迎回来，继续您的精彩旅程</text>
        </view>
        
        <!-- 登录卡片 -->
        <view class="login-card">
            <view class="form-content">
                <view class="form-group">
                    <label for="login-email" class="form-label">邮箱</label>
                    <view class="input-wrapper">
                        <i class="fas fa-envelope input-icon"></i>
                        <input
                            id="login-email"
                            v-model="loginForm.email"
                            type="text"
                            class="form-input"
                            placeholder="请输入邮箱"
                        />
                    </view>
                    <text v-if="loginErrors.email" class="error-message">{{loginErrors.email}}</text>
                </view>
                
                <view class="form-group">
                    <label for="login-password" class="form-label">密码</label>
                    <view class="input-wrapper">
                        <i class="fas fa-lock input-icon"></i>
                        <input
                            id="login-password"
                            v-model="loginForm.password"
                            :type="showLoginPassword ? 'text' : 'password'"
                            class="form-input"
                            placeholder="请输入密码"
                            @focus="handlePasswordFocus"
                        />
                        <i
                            :class="showLoginPassword ? 'fas fa-eye' : 'fas fa-eye-slash'"
                            class="toggle-password"
                            @click="showLoginPassword = !showLoginPassword"
                        ></i>
                    </view>
                    <text v-if="loginErrors.password" class="error-message">{{loginErrors.password}}</text>
                </view>
                
                <view class="form-actions">
                    <view class="remember-me">
                        <checkbox 
                            :checked="loginForm.rememberMe"
                            @change="loginForm.rememberMe = !loginForm.rememberMe"
                            class="checkbox"
                            color="#7B68EE"
                        />
                        <text class="checkbox-label">记住我</text>
                    </view>
                    <text class="forgot-password" @tap="handleForgotPassword">忘记密码？</text>
                </view>
                
                <button type="button" class="btn-primary auth-btn" :disabled="isLoading" @click="handleLogin">
                    <template v-if="isLoading">
                        <i class="fas fa-spinner fa-spin loading-icon"></i>
                        <text>登录中...</text>
                    </template>
                    <template v-else>登录</template>
                </button>
                
                <view class="divider">
                    <text>或</text>
                </view>
                
                <view class="social-login">
                    <button class="social-btn wechat" @tap="handleWxLogin">
                        <i class="fab fa-weixin"></i>
                        <text>微信登录</text>
                    </button>
                    <button class="social-btn qq" @tap="handleQqLogin">
                        <i class="fab fa-qq"></i>
                        <text>QQ登录</text>
                    </button>
                </view>
            </view>
        </view>
        
        <!-- 底部链接 -->
        <view class="login-link">
            <text class="login-text">还没有账户？</text>
            <text class="login-btn" @tap="goToRegister">立即注册</text>
        </view>
    </view>
</template>

<script>
import { ref, reactive } from 'vue'
import { login, register } from '@/api/user.js'
import { validateLoginForm, validateRegisterForm } from '@/utils/auth'
import { useUserStore } from '@/stores/user'
import { handleRegister as registerHandler } from '@/utils/auth'
import { handleApiError } from '@/utils/error-handler'
import { handleLoginSuccess, handleLoginError } from '@/utils/auth'

export default {
    data() {
        return {
            isLoading: false,
            showLoginPassword: false,
            loginForm: {
                email: '',
                password: '',
                rememberMe: false
            },
            loginErrors: {},
            isMobile: false,
            isDarkMode: false,
            // 键盘高度检测
            keyboardHeight: 0,
            isNavigating: false // 新增：防止重复点击
        }
    },
    mounted() {
        const systemInfo = uni.getSystemInfoSync();
		this.isMobile = systemInfo.windowWidth < 768;
		this.isTablet = systemInfo.windowWidth >= 768 && systemInfo.windowWidth < 1024;
		this.isDesktop = systemInfo.windowWidth >= 1024;
		this.isDarkMode = systemInfo.theme === 'dark';
        // 检查是否有保存的登录信息
        const savedEmail = uni.getStorageSync('savedEmail')
        if (savedEmail) {
            this.loginForm.email = savedEmail
            this.loginForm.rememberMe = true
        }
        
        // 监听键盘高度变化 (仅在App平台支持)
        // #ifdef APP-PLUS
        if (this.isMobile) {
            uni.onKeyboardHeightChange(res => {
                this.keyboardHeight = res.height;
            });
        }
        // #endif
    },
    methods: {
        async handleLogin() {
            // 用户点击登录按钮
            
            const errors = validateLoginForm(this.loginForm)
            this.loginErrors = errors
            
            if (Object.keys(errors).length > 0) {
              return
            }
            
            try {
              this.isLoading = true
              const response = await login(this.loginForm)
              console.log('Login response data:', response.data)
              console.log('User object structure:', response.data.user)
			  
			      // 新增：校验返回数据结构
			      if (!response) {
				  console.log(response)
			        throw new Error('登录失败：接口返回格式错误')
			      }
			  
              // 使用统一的登录成功处理
              handleLoginSuccess(response, this.loginForm, '/pages/home/home')
              
            } catch (error) {
              // 使用统一的登录失败处理
              handleLoginError(error, '登录')
            } finally {
              this.isLoading = false
            }
        },
        handleForgotPassword() {
            uni.showToast({ title: '功能开发中', icon: 'none' })
        },
        handleWxLogin() {
            uni.showToast({ title: '微信登录开发中', icon: 'none' })
        },
        handleQqLogin() {
            uni.showToast({ title: 'QQ登录开发中', icon: 'none' })
        },
        handlePasswordFocus() {
            // 处理密码输入框焦点事件，确保切换图标可以点击
            console.log('Password input focused')
        },
        goToRegister() {
            // 防止重复点击
            if (this.isNavigating) {
                return;
            }
            
            this.isNavigating = true;
            
            // 添加点击反馈
            uni.vibrateShort();
            
            // 使用延迟跳转，确保动画流畅
            setTimeout(() => {
                uni.navigateTo({
                    url: '/pages/register/register',
                    animationType: 'slide-in-right',
                    animationDuration: 300,
                    success: () => {
                        console.log('跳转到注册页面成功');
                    },
                    fail: (err) => {
                        console.error('跳转到注册页面失败:', err);
                        this.isNavigating = false;
                    },
                    complete: () => {
                        // 重置导航状态
                        setTimeout(() => {
                            this.isNavigating = false;
                        }, 500);
                    }
                });
            }, 100);
        }
    }
}
</script>

<style src="./login.css"></style>